package com.qimu.saiyou.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.qimu.saiyou.common.ErrorCode;
import com.qimu.saiyou.constant.CommonConstant;
import com.qimu.saiyou.exception.BusinessException;
import com.qimu.saiyou.exception.ThrowUtils;
import com.qimu.saiyou.mapper.QuestionMapper;
import com.qimu.saiyou.model.dto.question.PaperQuestionDTO;
import com.qimu.saiyou.model.dto.question.QuestionDTO;
import com.qimu.saiyou.model.dto.question.QuestionQueryRequest;
import com.qimu.saiyou.model.entity.Question;
import com.qimu.saiyou.model.entity.QuestionAnswer;
import com.qimu.saiyou.model.entity.User;
import com.qimu.saiyou.model.vo.QuestionAnswerVO;
import com.qimu.saiyou.model.vo.QuestionVO;
import com.qimu.saiyou.model.vo.UserVO;
import com.qimu.saiyou.service.PaperQuestionService;
import com.qimu.saiyou.service.QuestionAnswerService;
import com.qimu.saiyou.service.QuestionService;
import com.qimu.saiyou.service.UserService;
import com.qimu.saiyou.utils.SqlUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: FeiXiang
 * @description 针对表【question(题目)】的数据库操作Service实现
 * @createDate 2024-02-28 20:36:14
 */
@Service
public class QuestionServiceImpl extends MPJBaseServiceImpl<QuestionMapper, Question>
        implements QuestionService {
    @Resource
    private PaperQuestionService paperQuestionService;
    @Resource
    private UserService userService;

    @Resource
    private QuestionAnswerService questionAnswerService;

    @Override
    public void validQuestion(Question question, boolean add) {
        if (question == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String content = question.getContent();
        Integer type = question.getType();

        // 创建时，参数不能为空
        if (add) {
            ThrowUtils.throwIf(StringUtils.isAnyBlank(content) || ObjectUtils.isEmpty(type), ErrorCode.PARAMS_ERROR);
        }
        // 有参数则校验
        if (StringUtils.isNotBlank(content) && content.length() > 1000) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "题目过长");
        }
    }

    /**
     * 获取查询包装类
     *
     * @param questionQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Question> getQueryWrapper(QuestionQueryRequest questionQueryRequest) {
        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        if (questionQueryRequest == null) {
            return queryWrapper;
        }
        String searchText = questionQueryRequest.getSearchText();
        String sortField = questionQueryRequest.getSortField();
        String sortOrder = questionQueryRequest.getSortOrder();
        Long id = questionQueryRequest.getId();
        Long userId = questionQueryRequest.getUserId();

        // 拼接查询条件
        if (StringUtils.isNotBlank(searchText)) {
            queryWrapper.and(qw -> qw.like("content", searchText));
        }
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    @Override
    public QuestionVO getQuestionVO(Question question, HttpServletRequest request) {
        return getQuestionVO(question);
    }

    public QuestionVO getQuestionVO(Question question) {
        QuestionVO questionVO = QuestionVO.objToVo(question);
        long questionId = question.getId();
        // 1. 关联查询用户信息
        Long userId = question.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        questionVO.setUser(userVO);
        // 2. 获取答案信息
        QueryWrapper<QuestionAnswer> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(QuestionAnswer::getQuestionId, questionId);
        List<QuestionAnswerVO> questionAnswerVOList = questionAnswerService.list(queryWrapper).stream().map(QuestionAnswerVO::objToVo).collect(Collectors.toList());
        questionVO.setQuestionAnswerList(questionAnswerVOList);
        return questionVO;
    }

    public QuestionVO getQuestionNoRightVO(Question question) {
        QuestionVO questionVO = QuestionVO.objToVo(question);
        long questionId = question.getId();
        // 1. 关联查询用户信息
        Long userId = question.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        questionVO.setUser(userVO);
        // 2. 获取答案信息
        QueryWrapper<QuestionAnswer> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(QuestionAnswer::getQuestionId, questionId);
        List<QuestionAnswerVO> questionAnswerVOList = questionAnswerService.list(queryWrapper).stream().map(QuestionAnswerVO::objToNoRightVo).collect(Collectors.toList());
        // 打乱选项
        Collections.shuffle(questionAnswerVOList);
        questionVO.setQuestionAnswerList(questionAnswerVOList);
        return questionVO;
    }

    @Override
    public Page<QuestionVO> getQuestionNoRightVOPage(Page<Question> questionPage) {
        List<Question> questionList = questionPage.getRecords();
        Page<QuestionVO> questionVOPage = new Page<>(questionPage.getCurrent(), questionPage.getSize(), questionPage.getTotal());
        if (CollUtil.isEmpty(questionList)) {
            return questionVOPage;
        }
        // 1. 关联查询用户信息
        // 填充信息
        List<QuestionVO> questionVOList = questionList.stream().map(this::getQuestionNoRightVO).collect(Collectors.toList());
        questionVOPage.setRecords(questionVOList);
        return questionVOPage;
    }

    @Override
    public Page<QuestionVO> getQuestionVOPage(Page<Question> questionPage, HttpServletRequest request) {
        return getQuestionVOPage(questionPage);
    }

    @Override
    public Page<QuestionVO> getQuestionVOPage(Page<Question> questionPage) {
        List<Question> questionList = questionPage.getRecords();
        Page<QuestionVO> questionVOPage = new Page<>(questionPage.getCurrent(), questionPage.getSize(), questionPage.getTotal());
        if (CollUtil.isEmpty(questionList)) {
            return questionVOPage;
        }
        // 1. 关联查询用户信息
        // 填充信息
        List<QuestionVO> questionVOList = questionList.stream().map(this::getQuestionVO).collect(Collectors.toList());
        questionVOPage.setRecords(questionVOList);
        return questionVOPage;
    }

    @Override
    public Page<QuestionVO> getQuestionVOPageByDTO(Page<QuestionDTO> questionDTOPage) {
        List<QuestionDTO> questionList = questionDTOPage.getRecords();
        Page<QuestionVO> questionVOPage = new Page<>(questionDTOPage.getCurrent(), questionDTOPage.getSize(), questionDTOPage.getTotal());
        if (CollUtil.isEmpty(questionList)) {
            return questionVOPage;
        }
        List<QuestionVO> questionVOList = questionList.stream().map(questionDTO -> {
                    Question question = new Question();
                    BeanUtils.copyProperties(questionDTO, question);
                    return question;
                }).map(this::getQuestionVO).
                collect(Collectors.toList());
        questionVOPage.setRecords(questionVOList);
        return questionVOPage;
    }

    @Override
    public Page<QuestionVO> getQuestionPaperVOPageByDTO(Page<PaperQuestionDTO> questionDTOPage) {
        List<PaperQuestionDTO> questionList = questionDTOPage.getRecords();
        Page<QuestionVO> questionVOPage = new Page<>(questionDTOPage.getCurrent(), questionDTOPage.getSize(), questionDTOPage.getTotal());
        if (CollUtil.isEmpty(questionList)) {
            return questionVOPage;
        }
        List<QuestionVO> questionVOList = questionList.stream().map(paperQuestionDTO -> {
                    Question question = new Question();
                    BeanUtils.copyProperties(paperQuestionDTO, question);
                    return question;
                }).map(this::getQuestionVO).
                collect(Collectors.toList());
        questionVOPage.setRecords(questionVOList);
        return questionVOPage;
    }
}




